<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="appStore.device === 'mobile'" class="default-theme">
        <!--类目数据-->
        <pane size="16">
          <el-col>
            <!-- <div class="head-container">
              <el-input
                v-model="deptName"
                placeholder="请输入类目名称"
                clearable
                prefix-icon="Search"
                style="margin-bottom: 20px"
              />
            </div> -->
            <div class="head-container">
              <el-table 
                :data="deptOptions" 
                style="width: 100%"
                @row-click="handleRowClick"
                highlight-current-row
                :row-class-name="tableRowClassName"
              >
                <el-table-column 
                  prop="categoryName" 
                  label="类别名称"
                >
                  <template #default="scope">
                    <div class="category-item">
                      <div class="category-name">
                        <el-icon><Folder /></el-icon>
                        <span>{{ scope.row.categoryName }}</span>
                      </div>
                      <div class="category-actions">
                        <el-button
                          link
                          type="danger"
                          icon="Delete"
                          @click.stop="handleDeleteCategory(scope.row)"
                          v-hasPermi="['wlxz:category:remove']"
                        />
                      </div>
                    </div>
                  </template>
             
                </el-table-column>
              </el-table>
            </div>
          </el-col>
        </pane>
        <!--用户数据-->
        <pane size="84">
          <el-col>
            <el-form
              :model="queryParams"
              ref="queryRef"
              :inline="true"
              v-show="showSearch"
              label-width="68px"
              @submit.prevent
            >
              <!-- <el-form-item label="文档id" prop="fileId">
                <el-input
                  v-model="queryParams.fileId"
                  placeholder="请输入文档id"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item> -->
              <el-form-item label="文档名称" prop="fileName">
                <el-input
                  v-model="queryParams.fileName"
                  placeholder="请输入文档名称"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <!-- <el-form-item label="文档大小" prop="fileSize">
                <el-input
                  v-model="queryParams.fileSize"
                  placeholder="请输入文档大小"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item> -->
              <!-- <el-form-item label="文档格式" prop="fileFormat">
                <el-input
                  v-model="queryParams.fileFormat"
                  placeholder="请输入文档格式"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item> -->
              <!-- <el-form-item label="类目id" prop="categoryId">
                <el-input
                  v-model="queryParams.categoryId"
                  placeholder="请输入类目id"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item> -->
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery"
                  >搜索</el-button
                >
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="Plus"
                  @click="handleAddCategory"
                  v-hasPermi="['wlxz:category:add']"
                >新增类别</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="Plus"
                  @click="handleAdd"
                  v-hasPermi="['wlxz:filerecord:add']"
                >新增文档</el-button>
              </el-col>
              <!-- <el-col :span="1.5">
                <el-button
                  type="success"
                  plain
                  icon="Edit"
                  :disabled="single"
                  @click="handleUpdate"
                  v-hasPermi="['wlxz:filerecord:edit']"
                  >修改</el-button
                >
              </el-col> -->
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  plain
                  icon="Delete"
                  :disabled="multiple"
                  @click="handleDelete"
                  v-hasPermi="['wlxz:filerecord:remove']"
                  >删除</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="warning"
                  plain
                  icon="Download"
                  @click="handleExport"
                  v-hasPermi="['wlxz:filerecord:export']"
                  >导出</el-button
                >
              </el-col>
              <right-toolbar
                v-model:showSearch="showSearch"
                @queryTable="getList"
              ></right-toolbar>
            </el-row>

            <el-table
              v-loading="loading"
              :data="filerecordList"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" align="center" />
              <!-- <el-table-column label="主键id" align="center" prop="id" />
              <el-table-column label="文档id" align="center" prop="fileId" /> -->
              <el-table-column label="文档名称" align="left" prop="fileName" min-width="250" />
              <!-- <el-table-column label="文档大小" align="center" prop="fileSize" /> -->
              <el-table-column label="文档格式" align="center" prop="fileFormat" />
              <el-table-column label="上传时间" align="center" prop="createTime" />
              <el-table-column label="上传作者" align="center" prop="createBy" />
              <!-- <el-table-column label="类目id" align="center" prop="categoryId" /> -->
              <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                 <!--  <el-button
                    link
                    type="primary"
                    icon="Edit"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['wlxz:filerecord:edit']"
                    >修改</el-button
                  > -->
                  <el-button
                    link
                    type="primary"
                    icon="Delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['wlxz:filerecord:remove']"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-show="total > 0"
              :total="total"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              @pagination="getList"
            />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>

    <!-- 修改新增文档对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="filerecordRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上传文件" prop="file">
          <el-upload
            ref="uploadRef"
            :action="null"
            :auto-upload="false"
            :on-change="handleFileChange" 
            :before-upload="beforeFileUpload"
            multiple
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">请选择要上传的文档文件</div>
            </template>
          </el-upload>

          <!-- 添加文件列表和进度显示 -->
          <div class="upload-list">
            <div v-for="(file, index) in uploadFiles" :key="index" class="upload-item">
              <div class="file-info">
                <span class="file-name">{{ file.name }}</span>
                <span class="file-status" :class="file.status">{{ file.status }}</span>
              </div>
            </div>
          </div>

          <!-- 批量上传按钮 -->
          <div class="upload-actions" v-if="uploadFiles.length">
            <el-button type="primary" @click="startUpload">开始上传</el-button>
            <el-button @click="clearFiles">清空列表</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户导入对话框
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog> -->

    <!-- 添加新类别的对话框 -->
    <el-dialog :title="categoryTitle" v-model="categoryOpen" width="500px" append-to-body>
      <el-form 
        ref="categoryRef" 
        :model="categoryForm" 
        :rules="categoryRules" 
        label-width="80px"
        @submit.prevent
      >
        <el-form-item label="类别名称" prop="categoryName">
          <el-input 
            v-model="categoryForm.categoryName" 
            placeholder="请输入类别名称"
            @keyup.enter="submitCategoryForm"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitCategoryForm">确 定</el-button>
          <el-button @click="cancelCategory">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Filerecord">
// import { getToken } from "@/utils/auth";
import useAppStore from "@/store/modules/app";
// import {
//   changeUserStatus,
//   listUser,
//   resetUserPwd,
//   delUser,
//   getUser,
//   updateUser,
//   addUser,
// } from "@/api/system/user";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import { listCategory, addCategory, delCategory } from "@/api/wlxz/category";
import { Folder } from '@element-plus/icons-vue'
// const router = useRouter();
const appStore = useAppStore();
// const { proxy } = getCurrentInstance();

// const userList = ref([]);
// const open = ref(false);
// const loading = ref(true);
// const showSearch = ref(true);
// const ids = ref([]);
// const single = ref(true);
// const multiple = ref(true);
// const total = ref(0);
// const title = ref("");
// const dateRange = ref([]);
// const deptName = ref("");
const deptOptions = ref(undefined);
const enabledDeptOptions = ref(undefined);
// const initPassword = ref(undefined);
// const postOptions = ref([]);
// const roleOptions = ref([]);
// /*** 用户导入参数 */
// const upload = reactive({
//   // 是否显示弹出层（用户导入）
//   open: false,
//   // 弹出层标题（用户导入）
//   title: "",
//   // 是否禁用上传
//   isUploading: false,
//   // 是否更新已经存在的用户数据
//   updateSupport: 0,
//   // 设置上传的请求头部
//   headers: { Authorization: "Bearer " + getToken() },
//   // 上传的地址
//   url: import.meta.env.VITE_APP_BASE_API + "/system/user/importData",
// });

// const data = reactive({
//   form: {},
//   queryParams: {
//     pageNum: 1,
//     pageSize: 10,
//     userName: undefined,
//     phonenumber: undefined,
//     status: undefined,
//     deptId: undefined,
//   },
//   rules: {
//     userName: [
//       { required: true, message: "用户名称不能为空", trigger: "blur" },
//       { min: 2, max: 20, message: "用户名称长度必须介于 2 和 20 之间", trigger: "blur" },
//     ],
//     nickName: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
//     password: [
//       { required: true, message: "用户密码不能为空", trigger: "blur" },
//       { min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" },
//       {
//         pattern: /^[^<>"'|\\]+$/,
//         message: "不能包含非法字符：< > \" ' \\\ |",
//         trigger: "blur",
//       },
//     ],
//     email: [
//       { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] },
//     ],
//     phonenumber: [
//       {
//         pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
//         message: "请输入正确的手机号码",
//         trigger: "blur",
//       },
//     ],
//   },
// });

import {
  listFilerecord,
  getFilerecord,
  delFilerecord,
  addFilerecord,
  updateFilerecord,
} from "@/api/wlxz/filerecord";

const { proxy } = getCurrentInstance();

const filerecordList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    fileId: null,
    fileName: null,
    fileSize: null,
    fileFormat: null,
    categoryId: null,
  },
  rules: {
    file: [
      { required: true, message: '请选择上传文件', trigger: 'change' }
    ]
  },
});
// const { queryParams, form, rules } = toRefs(data);

const { queryParams, form, rules } = toRefs(data);

/** 根据名称筛选部门树 */
// watch(deptName, (val) => {
//   proxy.$refs["deptTreeRef"].filter(val);
// });

// /** 查询用户列表 */
// function getList() {
//   loading.value = true;
//   listUser(proxy.addDateRange(queryParams.value, dateRange.value)).then((res) => {
//     loading.value = false;
//     userList.value = res.rows;
//     total.value = res.total;
//   });
// }

/** 查询部门下拉树结构 */
// function getDeptTree() {
//   deptTreeSelect().then((response) => {
//     deptOptions.value = response.data;
//     enabledDeptOptions.value = filterDisabledDept(
//       JSON.parse(JSON.stringify(response.data))
//     );
//   });
// }
function getDeptTree() {
  listCategory().then((response) => {
    deptOptions.value = response.rows;
    enabledDeptOptions.value = filterDisabledDept(
      JSON.parse(JSON.stringify(response.rows))
    );
  });
}

/** 过滤禁用的部门 */
function filterDisabledDept(deptList) {
  return deptList.filter((dept) => {
    if (dept.disabled) {
      return false;
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children);
    }
    return true;
  });
}

/** 当前选中的类别ID */
const currentCategoryId = ref(null);
/** 上传文件对象 */
const uploadFile = ref(null);
/** 上传组件ref */
const uploadRef = ref(null);

/** 表格行点击事件 */
function handleRowClick(row) {
  currentCategoryId.value = row.categoryId;
  queryParams.value.categoryId = row.categoryId;
  handleQuery();
}

/** 查询文档列表 */
function getList() {
  loading.value = true;
  listFilerecord(queryParams.value).then((response) => {
    filerecordList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
// 表单重置
function reset() {
  form.value = {};
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
  uploadFile.value = null;
  proxy.resetForm("filerecordRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  if (!currentCategoryId.value) {
    proxy.$modal.msgError("请先选择一个类别");
    return;
  }
  reset();
  open.value = true;
  title.value = "添加文档";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getFilerecord(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改文档";
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除文档编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delFilerecord(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "wlxz/filerecord/export",
    {
      ...queryParams.value,
    },
    `filerecord_${new Date().getTime()}.xlsx`
  );
}

// 添加表格行样式
const tableRowClassName = ({row, rowIndex}) => {
  return 'category-row';
}

getDeptTree();
getList();

// 添加新类别的相关逻辑
const categoryTitle = ref("");
const categoryOpen = ref(false);
const categoryRef = ref(null);
const categoryForm = ref({
  categoryName: ""
});
const categoryRules = {
  categoryName: [
    { required: true, message: "类别名称不能为空", trigger: "blur" },
  ]
};

function handleAddCategory() {
  resetCategoryForm();
  categoryOpen.value = true;
  categoryTitle.value = "添加类别";
}

function cancelCategory() {
  categoryOpen.value = false;
  resetCategoryForm();
}

function resetCategoryForm() {
  categoryForm.value = {
    categoryName: ""
  };
  if (categoryRef.value) {
    categoryRef.value.resetFields();
  }
}

function submitCategoryForm() {
  categoryRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await addCategory(categoryForm.value);
        proxy.$modal.msgSuccess("新增成功");
        categoryOpen.value = false;
        getDeptTree(); // 重新获取类别列表
      } catch (error) {
        console.error("新增类别失败:", error);
        proxy.$modal.msgError("新增失败");
      }
    }
  });
}

// 文件数量超出限制
function handleExceed() {
  proxy.$modal.msgError("最多只能上传一个文件");
}

// 上传文件列表
const uploadFiles = ref([]);

// 文件选择变化
function handleFileChange(file) {
  // 添加文件到列表
  uploadFiles.value.push({
    raw: file.raw,
    name: file.name,
    status: 'waiting' // waiting, uploading, success, error
  });
}

// 开始上传
async function startUpload() {
  if (!currentCategoryId.value) {
    proxy.$modal.msgError("请先选择一个类别");
    return;
  }

  let hasError = false;

  // 逐个上传文件
  for (const file of uploadFiles.value) {
    if (file.status !== 'waiting') continue;
    
    try {
      file.status = 'uploading';
      
      // 上传文件并等待完成
      const response = await addFilerecord(currentCategoryId.value, file.raw);
      
      file.status = 'success';
      
      // 每个文件上传成功后刷新列表
      await getList();
      
      // 添加延迟，确保服务器有时间处理完上一个请求
      await new Promise(resolve => setTimeout(resolve, 500));
      
    } catch (error) {
      hasError = true;
      file.status = 'error';
      console.error("上传失败:", error);
      proxy.$modal.msgError(`文件 ${file.name} 上传失败`);
      // 继续上传下一个文件，而不是中断
    }
  }

  // 所有文件上传完成后的处理
  if (!hasError) {
    proxy.$modal.msgSuccess("所有文件上传完成");
    open.value = false;
    uploadFiles.value = [];
    if (uploadRef.value) {
      uploadRef.value.clearFiles();
    }
  } else {
    // 如果有错误，提示用户查看失败的文件
    proxy.$modal.msgWarning("部分文件上传失败，请查看详情");
  }
}

// 清空文件列表
function clearFiles() {
  uploadFiles.value = [];
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
}

// 上传前校验
function beforeFileUpload(file) {
  // 这里可以添加文件类型和大小的校验逻辑
  if (!currentCategoryId.value) {
    proxy.$modal.msgError("请先选择一个类别");
    return false;
  }
  return true;
}

// 添加删除类别的方法
function handleDeleteCategory(row) {
  proxy.$modal.confirm('是否确认删除类别名称为"' + row.categoryName + '"的数据项？').then(function() {
    return delCategory(row.id);
  }).then(() => {
    getDeptTree();
    currentCategoryId.value = null;
    queryParams.value.categoryId = null;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
</script>

<style scoped>
.category-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 10px;
}

.category-name {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.category-actions {
  opacity: 0;
  transition: opacity 0.2s ease-in-out;
}

/* 鼠标悬停时显示删除按钮 */
.category-item:hover .category-actions {
  opacity: 1;
}

/* 删除按钮样式 */
.category-actions :deep(.el-button) {
  padding: 4px 8px;
}

.category-name:hover {
  color: var(--el-color-primary);
}

:deep(.category-row) {
  cursor: pointer;
}

:deep(.category-row:hover) {
  background-color: var(--el-table-row-hover-bg-color);
}

:deep(.el-table__row.el-table__row--current) {
  background-color: var(--el-table-row-hover-bg-color);
}

.category-header {
  padding: 0 0 16px 0;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: center;
  padding-top: 20px;
}

.upload-list {
  margin-top: 10px;
}

.upload-item {
  padding: 8px;
  border: 1px solid #eee;
  margin-bottom: 8px;
  border-radius: 4px;
}

.file-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.file-name {
  color: #606266;
}

.file-status {
  font-size: 13px;
}

.file-status.success {
  color: #67C23A;
}

.file-status.error {
  color: #F56C6C;
}

.upload-actions {
  margin-top: 16px;
  display: flex;
  gap: 10px;
}
</style>
